package MainSecurity

import (
	"security/AESUtil"
	"math/rand"
	"strings"
)

var keyStore = make(map[string]string)

var versionPrefix = "VERSION("
var versionSuffix = ")"
var defaultVersion = versionPrefix + "0" + versionSuffix

var defaultkey = "123456789012345678901234567890AB"

/**已作废的key*/
var historykey = make(map[string]string)
/**只允许解密的key*/
var deonlykey = make(map[string]string)
/**加密与解密都允许的key*/
var endekey = make(map[string]string)

func AddKeyStore(vtype string, string,versionnum string,key string){
	if(vtype=="HISTORYKEY"){
		historykey[versionPrefix+versionnum+defaultVersion]=key
	}else if(vtype=="DEONLYKEY"){
		deonlykey[versionPrefix+versionnum+defaultVersion]=key
	}else{
		endekey[versionPrefix+versionnum+defaultVersion]=key
	}
}

func getEnKey()(string){
	//从endekey中随机抽取一个作为key
	if(len(endekey)!=0){
		var i = rand.Int()%len(endekey)
		var c =0
		for _,v := range endekey{
			if(c==i){
				return v
			}
			c++
		}
	}
	//如果没有找到，则使用默认的key
	return defaultkey
}

func getDeKey(demsg string)(string){
	if(strings.HasPrefix(demsg,versionPrefix)){
		var i = strings.Index(demsg,versionSuffix)
		var version = string(demsg[:i+1])

		var key1,found1 = endekey[version]
		if(found1){
			return key1
		}
		var key2,found2 = deonlykey[version]
		if(found2){
			return key2
		}
	}
	return defaultkey
}

func Encode(enmsg string)(string,error){
	result,err := AESUtil.EncryptStr(getEnKey(),enmsg)
	if(err!=nil){
		return "",err
	}
	return result,nil
}
func Decode(demsg string)(string,error){
	result,err := AESUtil.DecryptStr(getDeKey(demsg),demsg)
	if(err!=nil){
		return "",err
	}
	return result,nil
}


